package com.jinyang.baserouter.interceptor

import android.Manifest
import android.content.Context
import com.jinyang.baserouter.log
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import androidx.fragment.app.FragmentActivity
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.jinyang.baserouter.PATH_ACTIVITY_WEB
import com.jinyang.baserouter.utils.requestMyPermissions

/**
 * @Author: LiuJinYang
 * @CreateDate: 2021/12/8
 * @Description:ARouter路由拦截 验证运行时权限
 */
//priority: 拦截器可以定义优先级，如果有多个拦截器，会依次执行拦截器
@Interceptor(priority = 0)
class PermissionInterceptor : IInterceptor {
    private var context: Context? = null
    private var postcard: Postcard? = null
    private var callback: InterceptorCallback? = null
    override fun init(context: Context) {
        this.context = context
        log("PermissionInterceptor.init")
    }

    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        log("PermissionInterceptor.process")
        this.postcard = postcard
        this.callback = callback
        if (postcard.path == PATH_ACTIVITY_WEB) {
            log("PermissionInterceptor.process: path匹配，开始校验运行时权限")
            requestMyPermissions(
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                )
            ) {
                if (it) {
                    log("允许了权限申请")
                    callback.onContinue(postcard)
                } else {
                    log("拒绝了权限申请")
                }
            }
        }else{
            log("PermissionInterceptor.process: path不匹配，无需拦截")
            callback.onContinue(postcard)
        }
    }
}